<?php
class FriendsController extends AppController {

	public function beforeFilter() {
        parent::beforeFilter();
  	
        //create table in database for this exemple
      		 /* Load Model datasource */
      			App::import('Model', 'ConnectionManager');
      			$con = new ConnectionManager;
      			$cn = $con->getDataSource('default');
            /* message table schema */
      			$sql = "CREATE TABLE IF NOT EXISTS friends (
							id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
							ownerId INT,
							friendId INT,
							deleted BOOLEAN,
							created DATETIME DEFAULT NULL,
							modified DATETIME DEFAULT NULL
      								)";
      			$cn->query($sql);
    }
	
	public function add(){
		if ($this->request->is('get')) {
			$friendId = $this->request->params['pass']['0'];
			
			$this->Friend->create();
			
			$friend = $this->Friend->find('all', 
					array('conditions' => array(
						'Friend.ownerId =' => $this->Auth->user('id'),
						'Friend.friendId =' => $this->request->params['pass']['0']
						)));
			if(count($friend)>0){
				if( array_key_exists('Friend', $friend[0])){
					$this->Friend->id = $friend[0]['Friend']['id'];
					$this->Friend->saveField('deleted', false);
					
					$this->Session->setFlash(__('Als Freund angelegt!'));
					return $this->redirect(array('controller' => 'users','action' => 'profil', $friendId));
				}
			}else{
			
				$data['Friend']['ownerId'] = $this->Auth->user('id');
				$data['Friend']['friendId'] = $friendId;
				$data['Friend']['deleted'] = false;
				if($this->Friend->save($data)){
					$this->Session->setFlash(__('Als Freund angelegt!'));
					return $this->redirect(array('controller' => 'users','action' => 'profil', $friendId));
				}
			}
		}
	}
	
	public function delete(){
		if ($this->request->is('get')) {
			
			$this->Friend->id = $this->Friend->find('all', array('conditions' => array('Friend.ownerId =' => $this->Auth->user('id'), 'Friend.friendId =' => $this->request->params['pass']['0'])))[0]['Friend']['id'];
			$this->Friend->saveField('deleted', true);

			$this->Session->setFlash(__('Benutzer wurde von der Freundesliste entfernt!'));
			
			return $this->redirect(array('controller' => 'friends','action' => 'show', $this->Auth->user('id')));
		}
	}
	
	public function show(){
		if ($this->request->is('get')) {
			$this->loadModel('User');
			
			$friends =  $this->Friend->find('all', array('conditions' => array('Friend.ownerId =' => $this->Auth->user('id'), 'Friend.deleted =' => false)));
		
			for($i=0; $i< count($friends); $i++){
				$friend = $this->User->findByid($friends[$i]['Friend']['friendId']);
				$friends[$i] = $friend['User'];
			}
		
			$this->Session->write('friends', $friends);
		}
	}
}